from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.responses import JSONResponse
import os
import shutil
from typing import Optional
from docs_parser import parse_document, save_to_json

app = FastAPI(title="文档解析服务", description="提供文档解析的RESTful API接口")

@app.post("/parse-document")
async def parse_document_api(
    file: UploadFile = File(...),
    output_dir: Optional[str] = Form(None)
):
    """
    解析上传的文档文件
    
    Args:
        file: 上传的文档文件
        output_dir: 输出目录（可选，默认为'result'）
    
    Returns:
        JSON响应包含解析结果和文件信息
    """
    if not output_dir:
        output_dir = "result"
    
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    
    try:
        # 保存上传的文件
        file_path = os.path.join(output_dir, file.filename)
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        
        # 根据文件后缀调用相应的parser
        data = parse_document(file_path)
        
        # 保存JSON结果
        base_name = os.path.splitext(file.filename)[0]
        output_filename = f"{base_name}.json"
        output_path = os.path.join(output_dir, output_filename)
        save_to_json(data, output_path)
        
        return JSONResponse(content={
            "success": True,
            "message": "文档解析成功",
            "filename": file.filename,
            "output_path": output_path,
            "section_count": len(data['sections']) if 'sections' in data else 0
        })
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文档解析失败: {str(e)}")
    finally:
        # 清理上传的文件
        if os.path.exists(file_path):
            os.remove(file_path)

@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy", "message": "文档解析服务正常运行"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)